import random
import time
from os import write

import requests
from bs4 import BeautifulSoup

def fetch_douban_movie():
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
    }

    try:
        for s in range(0,225,25) :
            a=1
            print(f'第{a}页的数据')
            a=a+1
            url = f'https://movie.douban.com/top250?start={s}'
            respones = requests.get(url, headers=headers)
            # 检查响应是否成功
            respones.raise_for_status()
            # 第二个参数：制定使用的解析器，‘html.parser’是python自带的html解析器
            # soup：代表的是整个解析后的文档树
            soup = BeautifulSoup(respones.text, 'html.parser')
            # 找到所有的电影
            items = soup.find_all('div', class_='item')
            for item in items:
                title = item.find('span', class_='title').text
                print(title)

            time.sleep(random.uniform(1,3))  # 随机延迟


    except requests.exceptions.RequestException as e:
        print('请求失败',e)
    except Exception as e:
        print(e)


if __name__ == '__main__':
    fetch_douban_movie()